package cn.innosmart.aq.view.fragment;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.AssignBoxAdapter;
import cn.innosmart.aq.bean.BoxBean;
import cn.innosmart.aq.bean.Employee;
import cn.innosmart.aq.util.FragmentManagerTool;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.util.SystemConstant;

public class AssignedBoxFragment extends BaseFragment implements INetworkInteractUtil {
    private NetworkInteractUtil networkInteractUtil;
    private ListView lvAssignBox;
    private TextView tvEmpty;
    private Toolbar toolbar;
    private View.OnClickListener onNavigationClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FragmentManagerTool.popBackStackFragment(getActivity().getSupportFragmentManager());
        }
    };
    private Employee employee;
    private Menu menus;
    private ArrayList<BoxBean> boxBeans;
    //    private HashMap<>
    private ArrayList<String> assignedBoxs;
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_save:
                    JSONObject jsonParams = new JSONObject();
                    try {
                        jsonParams.put("assignTo", employee.id);
                        jsonParams.put("did", new JSONArray(JSON.toJSONString(assignedBoxs, true)));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    networkInteractUtil.updateAssignTo(jsonParams);
                    break;
            }
            return true;
        }
    };
    private AssignBoxAdapter assignBoxAdapter;
    private CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            BoxBean boxBean = (BoxBean) buttonView.getTag();
            if (isChecked) {
                if (!assignedBoxs.contains(boxBean.getHubId()))
                    assignedBoxs.add(boxBean.getHubId());
            } else {
                if (assignedBoxs.contains(boxBean.getHubId()))
                    assignedBoxs.remove(boxBean.getHubId());
            }
        }
    };

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        return inflater.inflate(R.layout.fragment_assign_box, null);
    }

    private void setBar() {
        toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
        ((ImageView) getActivity().findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        ((TextView)  getActivity().findViewById(R.id.tv_toolbar)).setText(getActivity().getString(R.string.box_list_title));
//        toolbar.setTitle(getActivity().getString(R.string.box_list_title));
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
//        toolbar.setNavigationOnClickListener(onNavigationClickListener);
        getActivity().findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManagerTool.popBackStackFragment(getActivity().getSupportFragmentManager());
            }
        });
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        networkInteractUtil = new NetworkInteractUtil(this);
        setBar();
        getData();
        lvAssignBox = (ListView) view.findViewById(R.id.lv_assign_box);
        assignBoxAdapter = new AssignBoxAdapter(getActivity(), boxBeans);
        lvAssignBox.setAdapter(assignBoxAdapter);
        tvEmpty = (TextView) view.findViewById(R.id.tv_empty);
        lvAssignBox.setEmptyView(tvEmpty);
        assignBoxAdapter.setOnCheckedChangeListener(onCheckedChangeListener);
    }

    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_assign_box, menu);
        menus = menu;
        super.onCreateOptionsMenu(menu, inflater);
    }

    private void getData() {
        if (boxBeans == null)
            boxBeans = new ArrayList<>();
        if (SystemConstant.boxBeanList != null) {
            for (BoxBean boxBean : SystemConstant.boxBeanList) {
                if (boxBean.getOwner().equals(SharedUtil.getInstance().readUserId()))
                    boxBeans.add(boxBean);
            }
        }
        if (assignedBoxs == null)
            assignedBoxs = new ArrayList<>();
        JSONObject jsonParams = new JSONObject();
        try {
            jsonParams.put("employeeid", employee.id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        networkInteractUtil.getEmployeeAssigned(jsonParams);
    }

    @Override
    public void onNetworkInteractAllOver(int ret) {

    }

    @Override
    public void onNetworkInteractOver(int ret, String flag, Object object) {
        hideLoadingDialog();
        if (flag.equals(networkInteractUtil.UPDATEASSIGNTO)) {
            switch (ret) {
                case 0:
                    showToast(getActivity().getString(R.string.assign_success));
                    FragmentManagerTool.popBackStackFragment(getActivity().getSupportFragmentManager());
                    break;
                case 1:
                default:
                    showToast(getActivity().getString(R.string.assign_failed));
                    break;
            }
        } else if (flag.equals(networkInteractUtil.GETEMPLOYEEASSIGNED)) {
            JSONObject jsonResponse = (JSONObject) object;
            JSONObject jsonUserInfo = null;
            JSONArray jsonAssigedInfo = null;
            assignedBoxs.clear();
            try {
                jsonUserInfo = jsonResponse.getJSONObject("userinfo");
                jsonAssigedInfo = jsonUserInfo.getJSONArray("assigned");
                for (int i = 0; i < jsonAssigedInfo.length(); i++) {
                    JSONObject jsonAssigned = jsonAssigedInfo.getJSONObject(i);
                    assignedBoxs.add(jsonAssigned.getString("id"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            switch (ret) {
                case 0:
                    assignBoxAdapter.refresh(assignedBoxs);
                    break;
                case 1:
                default:
                    break;
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        toolbar.setNavigationIcon(null);
    }
}
